#include "main.h"
#include "rgb_lcd.h"
#include "music_if.hpp"
#include "wm8978.hpp"

#include "ff.h"

#include "../lvgl/porting/lv_port.h"

#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"

TaskHandle_t lv_task;

void rtos_degug(void *arg)
{
    int i = 0;
    for (;;) {
        HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_0);
        vTaskDelay(300);
        auto ret = uxTaskGetStackHighWaterMark(lv_task);
        if (i != ret) {
            i = ret;
            printf("lv_task Stack: %d\n", (int)ret);
        }
    }
}

FRESULT init()
{
    lv_init();
    lv_port_disp_init();
    lv_port_indev_init();
    wmInit();

    static FATFS fs;
    return f_mount(&fs, "0:", 1);
}

void startUI();
void key_scan(void *);

void myapp()
{   
    if (init() != FR_OK) {
        auto *err_msg = lv_label_create(lv_scr_act());
        lv_label_set_text(err_msg, "FATFS mount failed");
        lv_obj_center(err_msg);
    } else {
        startUI();
    }

    lv_tick_set_cb(xTaskGetTickCount);

    xTaskCreate([](void *){ for (;;) { vTaskDelay(5); lv_timer_handler(); } }, "LVGL Task", 2048, nullptr, 2, &lv_task);
    xTaskCreate(key_scan, "Key Scan Task", 128, nullptr, 1, nullptr);
    xTaskCreate(rtos_degug, "LED Task", 128, nullptr, 1, nullptr);

    vTaskStartScheduler();
}

